package cn.sdack.go.users;

import cn.sdack.go.common.entities.users.AuthorityEntity;
import cn.sdack.go.common.entities.users.GroupEntity;
import cn.sdack.go.common.entities.users.UserEntity;
import cn.sdack.go.users.dao.AuthorityDao;
import cn.sdack.go.users.dao.GroupDao;
import cn.sdack.go.users.dao.RoleDao;
import cn.sdack.go.users.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;

@EntityScan("cn.sdack.go.common.entities.users")
@SpringBootApplication
public class UsersApplication {

    public static void main(String[] args) {
        SpringApplication.run(UsersApplication.class, args);
    }


    @Autowired
    private GroupDao groupDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private AuthorityDao authorityDao;

    @Autowired
    private RoleDao roleDao;
    @Bean
    public ExitCodeGenerator exitCodeGenerator() {
        Long count = groupDao.countByDelIsNull();
        if (count == 0L) {
            GroupEntity group = new GroupEntity();
            group.setName("DefaultGroup");
            group.setPrincipal("");
            groupDao.save(group);
            String code = UserEntity.Identity.SUPER.code;
            Long count1 = userDao.countByIdentity(code);
            if (count1 == 0L) {
                UserEntity user = new UserEntity();
                user.setNickname("super");
                user.setUsername("super");
                user.setEmail("123456@qq.com");
                user.setPhone("");
                user.setIdentity(code);
                user.setAccount("sdack");
                user.setGid(group.getId());
                userDao.save(user);
            }
        }
        AuthorityEntity entity = authorityDao.findByCodeAndGid("GroupAdmin", 0L);
        if (entity == null) {
            AuthorityEntity build = AuthorityEntity.builder().name("组织管理员")
                    .code("GroupAdmin").build();
            build.setGid(0L);
            authorityDao.save(build);
        }

        return () -> 32;
    }
}
